package com.qfedu.edu.service.impl;


import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qfedu.edu.exception.BusinessException;
import com.qfedu.edu.mapper.UserMapper;
import com.qfedu.edu.pojo.User;
import com.qfedu.edu.result.ResponseCode;
import com.qfedu.edu.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findAll() {
        return userMapper.selectList(new QueryWrapper<>());
    }

    @Override
    public User findUserById(Integer id) {
        if (id == null) {
            throw new BusinessException(400, "id不能为空");
        }
        try {
            return userMapper.selectById(id);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.SYS_ERROR);
        }
    }

    @Override
    public int addUser(User user) {
        if (user == null || StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION);
        }
        user.setVersion(1);
        user.setStatus(1);
        user.setDeleted(0);
        System.out.println(user);
        try {
            return userMapper.insert(user);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.SYS_ERROR);
        }
    }

    @Override
    public int updateUser(User user) {
        if (user == null || user.getId() == null || StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION);
        }
        System.out.println(user);
        User userSelect = userMapper.selectById(user.getId());
        if (userSelect == null) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION);
        }
        try {
            int version = userSelect.getVersion();
            BeanUtils.copyProperties(user, userSelect);
            userSelect.setVersion(version);
            return userMapper.updateById(userSelect);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.SYS_ERROR);
        }
    }
   @Override
    public int deleteById(Integer id) {
        if (id == null) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION);
        }
        try {
            return userMapper.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.SYS_ERROR);
        }
    }
}
